package common.collect;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import pojo.*;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 马泽朋
 * @version 1.0
 * @date 2019/10/22 18:58
 */
public class BaseCollectUitls {
    private String domain;
    private Map<String, Object> map;

    /**
     * 获取所有图书集合url
     * @param url 起始url用{}作为可变参数
     * @param start 起始位置
     * @param end 结束位置
     * @return 返回所有连接集合
     */
    public static List<String> getChapterSet(String url,int start,int end){
        //String template = "{}爱{}，就像老鼠爱大米";
        //String str = StrUtil.format(template, "我", "你"); //str -> 我爱你，就像老鼠爱大米
        List<String> list = new ArrayList<>();
        for (int i =start; i<=end; i++){
            list.add(StrUtil.format(url,i));
        }
        return list;
    }

    /**
     * 获得一页url图书url地址
     * @param chapterRules 获得页面图书解析span[class=sm]
     * @param urlList 请求url
     * @return 返回一个包含uuid字典
     */
    public static Map<String,Object> getTheBookAddress(String chapterRules, String urlList){
        //请求html界面

        String html = HttpUtil.get(urlList);
        //解析html字符串
        Document parse = Jsoup.parse(html);
        //抽取数据
        Elements select = parse.select(chapterRules);
        //存储采集结果
        Map<String,Object> map = new HashMap<>();
        //遍历抽取到的记录，抽取详细结果放入结果字典
        for (Element element : select) {
            //生成唯一uuid
            String simpleUUID = IdUtil.simpleUUID();
            //抽取小说连接
            String attr = element.select("a").attr("href");
            //做一个规避，目标站地址有坑
            if (attr==null || attr.trim()==""){
                continue;
            }
            map.put(simpleUUID, attr);
        }

        return map;
    }

    /**
     * 采集单本本小说信息，并采集章节uri地址
     * @param domain 网站主域名
     * @param list 采集地址对象带uuid
     * @param classificationList 分类集合
     * @return
     */
    public static List<Book> collectBriefInformationAndChapters(String domain, List<CollectSingle> list, List<Classification> classificationList) throws IOException {
        //存放结果
        List<Book> books = new ArrayList<>();
        for (CollectSingle collectSingle : list) {

            //请求页面地址
            String html = HttpUtil.get(domain + collectSingle.getCollection());

            //解析string为dom对象
            Document parse = Jsoup.parse(html);
            //获取书籍名称
            String name = parse.select("div[class=rt]").select("h1").text();

            //作者等信息解析
            Elements select = parse.select("div[class=msg]");

            //作者
            String author = select.select("em").get(0).text();
            //完结状态
            int state = select.select("em").get(1).text().equals("状态：连载中") ? 1 : 0;

            //获取简介信息
            String intro = parse.select("div[class=intro]").text();
            int classification = 0;
            System.out.println(name+">>>"+state+">>>"+author);
            //分类信息
            String cation = parse.select("div[class=place] a").get(1).text();
            for (Classification classifications : classificationList) {
                if (classifications.getCategoryName().trim().equals(cation)){
                    classification = classifications.getCategoryId();
                    System.out.println(classification);
                }
            }
            //图片URL
            String imgURL = parse.select("div[class=lf]").select("img").attr("src");
            String cover = getImg(imgURL);
            //生成书籍对象
            Book book = new Book(collectSingle.getUuid(), name, author, state, classification, 0, cover, intro);
            //放入结果
            books.add(book);
        }
        return books;
    }

    /**
     * 图片生成uri工具
     * @param ur 图片url地址
     * @return dataURI字符串
     * @throws IOException
     */
    public static String getImg(String ur) {

        String encode= null;
        //规避丢失图片
        String repetition = "https://www.88dushu.com/modules/article/images/nocover.jpg";
        if (repetition.equals(ur)){
            File file = new File("img/暂无图片.jpg");
            encode = "data:image/png;base64,"+ Base64.encode(file);
        }else {

            try {
                URL url = new URL(ur);

                //打开链接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                //设置请求方式为"GET"
                conn.setRequestMethod("GET");

                //超时响应时间为5秒
                conn.setConnectTimeout(5 * 1000);

                //通过输入流获取图片数据
                InputStream inStream = conn.getInputStream();
                encode = "data:image/png;base64,"+ Base64.encode(inStream);
            } catch (IOException e) {
                File file = new File("img/暂无图片.jpg");
                System.out.println("图片丢失");
                encode = "data:image/png;base64,"+ Base64.encode(file);
                e.printStackTrace();
            }
        }
        //返回一个dataURI
        return encode;
    }

    /**
     * 采集章节地址
     * @param domain 网站主域名
     * @param list 单本小说url地址
     * @return 采集状态
     */
    public static List<Chapter> collectionChapter(String domain, List<CollectSingle> list){
        //存放章节结果
        List<Chapter> chapters = new ArrayList<>();
        //遍历本页小说url单本
        for (CollectSingle collectSingle : list) {
            //请求页面地址
            String html = HttpUtil.get(domain + collectSingle.getCollection());

            //解析string为dom对象
            Document parse = Jsoup.parse(html);
            //采集章节规则
            Elements select = parse.select("div[class=mulu] ul li a");
            for (Element element : select) {
                //将信息放入结果集
                chapters.add(new Chapter(collectSingle.getUuid(), collectSingle.getCollection()+element.attr("href"), element.text()));
                System.out.println(element.text());
            }
        }
        return chapters;
    }

    /**
     * 采集小说文本
     * @param list 小说章节集合
     * @return 文本集合
     */
    public static List<NovelText> collectionNovelText(String domain,List<Chapter> list){
        List<NovelText> chapters = new ArrayList<>();
        for (Chapter chapter : list) {
            //请求页面地址
            String html = HttpUtil.get(domain+chapter.getSite());

            //解析string为dom对象
            Document parse = Jsoup.parse(html);
            //采集到text文本
            String text = parse.select("div[class=yd_text2]").text();
            boolean add = chapters.add(new NovelText(chapter.getUuid(), chapter.getName(), text));
            if (add){
                System.out.println(chapter.getName()+">>>>>>>>成功");
            }else {
                System.out.println(chapter.getName()+">>>>>>>>失败");
            }
        }
        return chapters;

    }
}
